/**
 * 字符串去全部空格
 * @param  {String} str 目标字符串
 * @return {[type]}     去掉空格后的字符串
 */
export const trim = function (str = '') {
  return str.replace(/\s/ig, '')
}

/**
 * 将汉字转换成2个字符，并切割制定长度的字符串
 * @param  {String} str 目标字符串
 * @param  {Number} len 切割长度
 * @return {[type]}     切割转换后的字符串
 */
export const sliceString = function (str = '', len = 0) {
  if (str === '') {
    return str
  }

  if (calculateChineseCharLength(str) < len) {
    return str
  }

  // 再做截取
  let charLength = 0
  for (var i = 0; i < str.length; i++) {
    const sonStr = str.charAt(i)
    if (sonStr && sonStr !== ' ') {
      encodeURI(sonStr).length > 2 ? charLength += 2 : charLength += 1
    } else {
      charLength += 1
    }

    if (charLength >= len) {
      const subLen = charLength === len ? i + 1 : i
      return str.substr(0, subLen)
    }
  }
}

/**
 * 计算字符长度，中文字符会当2个字符计算
 * @param  {String} str [description]
 * @return {[type]}     [description]
 */
export const calculateChineseCharLength = function (str = '') {
  if (str === '') {
    return 0
  }

  // 计算长度
  const strLen = str.length
  const chineseStr = str.replace(/[^\u4e00-\u9fa5]/gi, '')
  const chineseStrLen = chineseStr.length

  const length = chineseStrLen * 2 + strLen - chineseStrLen
  return length
}
